package com.lv.common.widget

import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.lv.common.R

/**
 * 作者： ygx
 * 创建日期：2024/11/22 1:44 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class InterceptingRecyclerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : RecyclerView(context, attrs, defStyle) {

    private var parentViewPager2: ViewPager2? = null

    init {
        // 通过布局文件初始化时的AttributeSet来查找父ViewPager2
        if (attrs != null) {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.InterceptingRecyclerView)
            val parentId = typedArray.getResourceId(R.styleable.InterceptingRecyclerView_parentViewPagerId, View.NO_ID)
            if (parentId != View.NO_ID) {
                parentViewPager2 = findViewById(parentId) as? ViewPager2
            }
            typedArray.recycle()
        }
    }

    override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
        if (parentViewPager2 != null && e.action == MotionEvent.ACTION_DOWN) {
            // 检查触摸点是否在ViewPager2的区域内
            val parentLocation = IntArray(2)
            parentViewPager2!!.getLocationOnScreen(parentLocation)
            val x = e.rawX.toInt()
            val y = e.rawY.toInt()
            val viewPagerBounds = Rect(
                parentLocation[0],
                parentLocation[1],
                parentLocation[0] + parentViewPager2!!.width,
                parentLocation[1] + parentViewPager2!!.height
            )
            if (viewPagerBounds.contains(x, y)) {
                // 触摸点在ViewPager2区域内，不拦截事件
                return false
            }
        }
        // 触摸点不在ViewPager2区域内，拦截事件
        return true
    }
}